<script setup>
import { User, Lock,Eleme,Phone,Message } from '@element-plus/icons-vue'
import { ElNotification} from 'element-plus'
import {ref, reactive, onMounted} from 'vue'
import axios from "axios";
import router from "@/router/index.js";
import {loginUser, registerUser} from '@/api/getData.js'
import {ElMessage} from 'element-plus';
import {setStorage} from '@/utils/localStorage.js'
import Sidentify from "@/views/login/Sidentify.vue";
import store from "@/store/index.js";

//控制注册与登录表单的显示， 默认显示登录
const isRegister = ref(false)

// 定义变量开始
//注册
let registerData = reactive({
  userId:'',
  password:'',
  rePassword:'',
  username:'',
  role:'',
})

//登录
let loginData=reactive({
  username:'',
  password:''
})

//校验密码的函数
const checkRePassword = (rule,value,callback)=>{
  if(value===''){
    callback(new Error('请再次确认密码'))
  }else if(value !== registerData.value.password){
    callback(new Error('请确保两次输入的密码一致'))
  }else{
    callback()
  }
}
// 表单验证
//定义表单校验规则
const rules={
  // userId:[
  //   {required:true,message:'请输入用户名',trigger:'blur'},
  //   {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  // ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ],
  rePassword:[
    {validator:checkRePassword,trigger:'blur'}
  ],
  username:[
    {required:true,message:'请输入昵称',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ],
  role:[
    {required:true,message:'请输入身份',trigger:'blur'},
    {min:1,max:20,message:'长度应为1~20位非空字符',trigger:'blur'}
  ]
}
// 按钮节流
const buttonLoading = ref(false)

//登录请求函数
const login2 = () => {
  buttonLoading.value = true;
  //调用接口
  loginUser(loginData).then(res => {
    if (res != -1) { //登录功能
      if(!sidentifyMode.value){
        ElMessage({ type: 'error', message: '验证码不能为空！' })
        return
      }
      // 验证验证码是否正确
      if (sidentifyMode.value != identifyCode.value) {
        ElMessage({type: 'error', message: '验证码错误'})
        refreshCode()
        return
      console.log('1111111111111111')
      }else{
        //登录成功提示
        ElMessage.success("登录成功");
        //保存token,用户信息, 用户菜单到浏览器缓存
        setStorage("Token", res.datas.token);
        setStorage("userInfo", JSON.stringify(res.datas));
        //页面跳转
        router.push("/homeView");
      }
    }
    setTimeout(() => {
      buttonLoading.value = false;
    }, 2000)
  })
}

const register = ()=>{
  registerUser(registerData).then(res =>{
    if(res != -1){
      ElMessage.success("注册成功")
      setStorage("Token", res.datas.token);
      setStorage("UserInfo",JSON.stringify(res.datas));
      //页面跳转
      router.push('/login');
    }
    setTimeout(() => {
      buttonLoading.value = false;
    }, 2000)
  })
}
// 登录
function login(){
  store.dispatch('loginMoudle/login',{'username':loginData.username,'password':loginData.password})
}
// //注册请求函数
// function register(){
//   store.dispatch('registerMoudle/register',
//       {
//         'userId':registerData.userId,
//         'password':registerData.password,
//         'username':registerData.username,
//         'phone':registerData.phone,
//         'code':registerData.code,
//         'email':registerData.email
//       })
// }

//清空
const clearRegisterData = ()=>{
  registerData.value={
    userId:'',
    password:'',
    rePassword:'',
    username:'',
    role:'',
  }
}


//验证码
let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdefjhijklinopqrsduvwxyz') //验证码出现的数字和字母
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
})

// 生成随机数
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}
</script>



<template>
  <div  class="container">
    <el-card class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>

        <el-form-item prop="userId">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.userId"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码" v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="Eleme" placeholder="请输入昵称" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="role">
          <el-input :prefix-icon="Phone" placeholder="请输入身份" v-model="registerData.role"></el-input>
        </el-form-item>

        <!-- 注册按钮 -->
      <el-form-item>
        <el-button class="button" type="primary" auto-insert-space @click="register">
          注册
        </el-button>
      </el-form-item>
      <el-form-item class="flex">
        <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
          ← 返回
        </el-link>
      </el-form-item>
      </el-form>


      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="loginData" :rules="rules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="userId">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="loginData.password"></el-input>
        </el-form-item>

        <el-form-item>
          <el-input :prefix-icon="Lock" style="width: 300px" placeholder="请输入验证码" v-model="sidentifyMode" clearable></el-input>
          <div class="code" @click="refreshCode">
            <Sidentify :identifyCode="identifyCode"></Sidentify>
          </div>
        </el-form-item>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>

        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>



<style lang="scss" >
.container{
  margin: 0;
  min-height: 100vh;
  background-color: #cce5ff;
  background-image:
      radial-gradient(closest-side,rgba(112, 134, 182, 1),rgba(222, 243, 248, 0));
  background-size:
      130vmax 130vmax,
      80vmax 80vmax,
      90vmax 90vmax,
      110vmax 110vmax,
      90vmax 90vmax;
  background-position:
      -80vmax -80vmax,
      60vmax -30vmax,
      10vmax 10vmax,
      -30vmax -10vmax,
      50vmax 50vmax;
  background-repeat: no-repeat;
  animation: 8s movement linear infinite;

  body::after {
    content: '';
    display: block;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
  }

  @keyframes movement {
    0%, 100% {
      background-size:
          130vmax 130vmax,
          80vmax 80vmax,
          90vmax 90vmax,
          110vmax 110vmax,
          90vmax 90vmax;
      background-position:
          -80vmax -80vmax,
          60vmax -30vmax,
          10vmax 10vmax,
          -30vmax -10vmax,
          50vmax 50vmax;
    }
    25% {
      background-size:
          100vmax 100vmax,
          90vmax 90vmax,
          100vmax 100vmax,
          90vmax 90vmax,
          60vmax 60vmax;
      background-position:
          -60vmax -90vmax,
          50vmax -40vmax,
          0vmax -20vmax,
          -40vmax -20vmax,
          40vmax 60vmax;
    }
    50% {
      background-size:
          80vmax 80vmax,
          110vmax 110vmax,
          80vmax 80vmax,
          60vmax 60vmax,
          80vmax 80vmax;
      background-position:
          -50vmax -70vmax,
          40vmax -30vmax,
          10vmax 0vmax,
          20vmax 10vmax,
          30vmax 70vmax;
    }
    75% {
      background-size:
          90vmax 90vmax,
          90vmax 90vmax,
          100vmax 100vmax,
          90vmax 90vmax,
          70vmax 70vmax;
      background-position:
          -50vmax -40vmax,
          50vmax -30vmax,
          20vmax 0vmax,
          -10vmax 10vmax,
          40vmax 60vmax;
    }
  }
}

.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;
  width: 500px;
  z-index: 1000;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
.title {
  margin: 0 auto;
}
.button {
  width: 100%;
}
.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
}
.code{
  padding-left: 30px;
  padding-top: 10px;
}
</style>